package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.truck;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.bo.StatisticPlanBo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.CTruckClass;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.CTrucks;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysUser;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysUserPlantConn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.TruckClassExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.TruckClassExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ICTruckClassService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ICTrucksService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ISysUserPlantConnService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.GetAllPdtPlanVo;
import com.xiaoxu.intranetweb.util.SzResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.UUID;
import java.util.concurrent.Future;

@Component
public class TruckClassBu {
    @Autowired
    private ICTruckClassService iCTruckClassService;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private SysLogBu sysLogBu;
    @Autowired
    private ISysUserPlantConnService userPlantConnService;
    @Autowired
    private ICTrucksService iCTrucksService;


    //    所有车辆类型
    public SzResult getTruckClass(String plantId) {
        QueryWrapper<CTruckClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("TRUCKCLASS_DELETED", 0);
        queryWrapper.orderByAsc("TRUCKCLASS_ID");
        queryWrapper.eq("DATA_FROM", plantId);
        List<CTruckClass> cTrucksInfoList = iCTruckClassService.list(queryWrapper);
        return SzResult.success(cTrucksInfoList);
    }

    //新增车辆类型
    public SzResult addTruckClass(String truckClass, String remark, String token,String plantId) throws Exception {
       String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        CTruckClass cTruckClass = new CTruckClass();
        QueryWrapper<CTruckClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("TRUCKCLASS_CLASS", truckClass);
        queryWrapper.eq("DATA_FROM", plantId);
        CTruckClass one = iCTruckClassService.getOne(queryWrapper);
        if (one != null) {
            return SzResult.error("该车辆类型已存在");
        }
        cTruckClass.setTruckclassClass(truckClass);
        if (remark != null) {
            cTruckClass.setTruckclassRemark(remark);
        }
//            cTruckClass.setTruckclassId(uuid);
//        找到TruckclassId最大那个值
        QueryWrapper<CTruckClass> maxIdQueryWrapper = new QueryWrapper<>();
        maxIdQueryWrapper.orderByDesc("TRUCKCLASS_ID");
        maxIdQueryWrapper.last("limit 1");
        maxIdQueryWrapper.eq("DATA_FROM", plantId);
        CTruckClass truckClass1 = iCTruckClassService.getOne(maxIdQueryWrapper);
        if (truckClass1 != null) {
            BigDecimal truckclassId = truckClass1.getTruckclassId();
            String trucksId1 = String.valueOf((truckclassId.intValue() + 1));
            cTruckClass.setTruckclassId(new BigDecimal(trucksId1));
        } else {
            cTruckClass.setTruckclassId(new BigDecimal(1));
        }
        cTruckClass.setId(uuid);
        cTruckClass.setTruckclassDeleted(0);
        cTruckClass.setDataFrom(plantId);
        iCTruckClassService.save(cTruckClass);
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        sysLogBu.logRecord("新增车辆类型", user.getTrueName(), "新增了车辆类型为" + truckClass + "的车辆类型", plantId);
        return SzResult.Success();
    }

    //修改车辆类型
    public SzResult updateTruckClass(String id, String truckClass, String remark, String token,String plantId) throws Exception {
        QueryWrapper<CTruckClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        queryWrapper.eq("TRUCKCLASS_DELETED", 0);
        queryWrapper.eq("DATA_FROM", plantId);
        CTruckClass one = iCTruckClassService.getOne(queryWrapper);
        if (one == null) {
            return SzResult.error("该车辆类型不存在");
        }
        if (truckClass != null) {
            QueryWrapper<CTruckClass> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("TRUCKCLASS_CLASS", truckClass);
            queryWrapper1.eq("TRUCKCLASS_DELETED", 0);
            queryWrapper1.eq("DATA_FROM", plantId);
            queryWrapper1.ne("ID", id);
            CTruckClass one1 = iCTruckClassService.getOne(queryWrapper1);
            if (one1 != null) {
                return SzResult.error("该车辆类型已存在");
            }
            one.setTruckclassClass(truckClass);
        }
        if (remark != null) {
            one.setTruckclassRemark(remark);
        }
        iCTruckClassService.updateById(one);
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        sysLogBu.logRecord("修改车辆类型", user.getTrueName(), "修改了车辆类型为" + truckClass + "的车辆类型", plantId);
        return SzResult.Success();
    }

    //删除车辆类型
    public SzResult deleteTruckClass(String id, String token,String plantId) throws Exception {

        QueryWrapper<CTruckClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        queryWrapper.eq("TRUCKCLASS_DELETED", 0);
        queryWrapper.eq("DATA_FROM", plantId);
        CTruckClass one = iCTruckClassService.getOne(queryWrapper);
        if (one == null) {
            return SzResult.error("该车辆类型不存在或已被删除");
        }
    /*    BigDecimal truckclassId = one.getTruckclassId();
        QueryWrapper<CTrucks> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("TRUCKS_TYPE", truckclassId);
        queryWrapper1.eq("TRUCKS_DELETED", 0);
        queryWrapper1.last("limit 1");
        CTrucks one1 = iCTrucksService.getOne(queryWrapper1);
        if (one1 != null) {
            return SzResult.error("该车辆类型下已有车辆，不允许删除");
        }*/


        one.setTruckclassDeleted(1);
        one.setDownedID1(0);
        iCTruckClassService.updateById(one);
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        sysLogBu.logRecord("删除车辆类型", user.getTrueName(), "删除了车辆类型为" + one.getTruckclassClass() + "的车辆类型", plantId);
        return SzResult.Success();
    }

    @Async
    public Future<List<TruckClassExcelEn>> exportExcel(List<Map<String, Object>> fields, List<Map<String, Object>> ids, String filename, Boolean isHeader, String mode, Boolean original, Map<String, String> pager, Map<String, String> form, String sheetName, HttpServletResponse response, String plantId, String truckclassId, String truckclassClass, String truckclassRemark) {
        List<Map<String, Object>> newIds = new ArrayList<>();
//        最终数据
        List<TruckClassExcelEn> list = new ArrayList<>();
        try {
            switch (mode) {
                case "current":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为NoticeExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        TruckClassExcelEn truckClassExcelEn = TruckClassExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {

                            if (entry.getKey().equals("truckclassId")) {
                                if (entry.getValue() != null) {
                                    truckClassExcelEn.setTruckclassId(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("truckclassClass")) {
                                if (entry.getValue() != null) {
                                    truckClassExcelEn.setTruckclassClass(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("truckclassRemark")) {
                                if (entry.getValue() != null) {
                                    truckClassExcelEn.setTruckclassRemark(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(truckClassExcelEn);
                    }
                    break;
                case "all":
                    QueryWrapper<CTruckClass> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("TRUCKCLASS_DELETED", 0);
                    queryWrapper.eq(truckclassId != null && !truckclassId.equals(""), "TRUCKCLASS_ID", truckclassId);
                    queryWrapper.like(truckclassClass != null && !truckclassClass.equals(""), "TRUCKCLASS_CLASS", truckclassClass);
                    queryWrapper.like(truckclassRemark != null && !truckclassRemark.equals(""), "TRUCKCLASS_REMARK", truckclassRemark);
                    queryWrapper.eq(plantId != null && !plantId.equals(""), "DATA_FROM", plantId);
                    List<CTruckClass> cTruckClasses = iCTruckClassService.list(queryWrapper);
                    for (CTruckClass cTruckClass : cTruckClasses) {
                        TruckClassExcelEn truckClassExcelEn = TruckClassExcelEn.builder()
                                .truckclassId(Optional.ofNullable(cTruckClass.getTruckclassId()).map(Object::toString).orElse(""))
                                .truckclassClass(Optional.ofNullable(cTruckClass.getTruckclassClass()).map(Object::toString).orElse(""))
                                .truckclassRemark(Optional.ofNullable(cTruckClass.getTruckclassRemark()).map(Object::toString).orElse(""))
                                .build();
                        list.add(truckClassExcelEn);
                    }
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为NoticeExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        TruckClassExcelEn truckClassExcelEn = TruckClassExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {

                            if (entry.getKey().equals("truckclassId")) {
                                if (entry.getValue() != null) {
                                    truckClassExcelEn.setTruckclassId(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("truckclassClass")) {
                                if (entry.getValue() != null) {
                                    truckClassExcelEn.setTruckclassClass(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("truckclassRemark")) {
                                if (entry.getValue() != null) {
                                    truckClassExcelEn.setTruckclassRemark(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(truckClassExcelEn);
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(list);

    }
}
